package com.sky.dish.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.github.yulichang.query.MPJLambdaQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.sky.client.CategoryClient;
import com.sky.dish.service.IDishFlavorService;
import com.sky.dish.service.IDishService;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.result.PageResult;
import com.sky.result.Result;

import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-07-19
 */
@RestController
@RequestMapping("/{userType}/dish")
@RequiredArgsConstructor
@Slf4j
@Api(tags = "菜品相关接口")
public class DishController {
    private final IDishService dishService;
    private final IDishFlavorService dishFlavorService;
    private final RedisTemplate redisTemplate;
    private final CategoryClient categoryClient;

    @ApiOperation("新增菜品")
    @PostMapping("")
    public Result<String> saveWithFlavor(@RequestBody DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishService.save(dish);
        //同时要插入多条口味，对应这里的菜品id
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (CollectionUtils.isNotEmpty(flavors)) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dish.getId());
            }
        }
        boolean result = dishFlavorService.saveBatch(dishDTO.getFlavors());
        if (!result) {
            return Result.error("新增菜品失败");
        }
        return Result.success();
    }

    @ApiOperation("根据id查询菜品")
    @GetMapping("/{id}")
    public Result<DishVO> getById(@PathVariable Long id) {
        Dish dish = dishService.getById(id);
        DishVO dishVO = BeanUtil.copyProperties(dish, DishVO.class);
        return Result.success(dishVO);
    }

    @ApiOperation("根据分类id查询所有菜品")
    @GetMapping("/list")
    public Result<List<DishVO>> listByCategoryId(@PathVariable String userType, Long categoryId) {
        if (StrUtil.equals("admin", userType)) {
            List<Dish> dishes = dishService.lambdaQuery()
                    .eq(Dish::getCategoryId, categoryId)
                    .list();
            List<DishVO> dishVOList = BeanUtil.copyToList(dishes, DishVO.class);
            return Result.success(dishVOList);
        } else if (StrUtil.equals("user", userType)) {
            //先查询redis里面有没有缓存数据，有的话就不用查询数据库
            String key = "dish_" + categoryId;
            List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key);
            if (ArrayUtil.isNotEmpty(list)) {
                return Result.success(list);
            }

            List<Dish> dish = dishService.lambdaQuery()
                    .eq(Dish::getCategoryId, categoryId)
                    .list();
            List<DishVO> dishVOList = BeanUtil.copyToList(dish, DishVO.class);
            //根据菜品查询对应的口味
            for (DishVO d : dishVOList) {
                d.setFlavors(dishFlavorService.lambdaQuery()
                        .eq(DishFlavor::getDishId, d.getId())
                        .list());
            }
            redisTemplate.opsForValue().set(key, dishVOList);
            return Result.success(dishVOList);
        } else {
            return Result.error("用户类型错误");
        }
    }

    @GetMapping("/page")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO) {
        //构建mp分页对象
        Page<Dish> page = dishPageQueryDTO.toPage();
        Integer categoryId = dishPageQueryDTO.getCategoryId();
        String name = dishPageQueryDTO.getName();
        Integer status = dishPageQueryDTO.getStatus();
        //join连表查询失败，要的话得加上category的mapper文件，不符合微服务的设计

//        MPJLambdaWrapper<Dish> wrapper = new MPJLambdaWrapper<Dish>()
//                .eq(categoryId != null, Dish::getCategoryId, categoryId)
//                .like(StrUtil.isNotBlank(name), Dish::getName, name)
//                .eq(status != null, Dish::getStatus, status)
//                .leftJoin(Category.class, Category::getId, Dish::getCategoryId);
//        Page<DishVO> dishVOPage = dishService.selectJoinListPage(page, DishVO.class, wrapper);
        Page<Dish> dishPage = dishService.lambdaQuery()
                .eq(categoryId != null, Dish::getCategoryId, categoryId)
                .like(StrUtil.isNotBlank(name), Dish::getName, name)
                .eq(status != null, Dish::getStatus, status)
                .page(page);
        List<DishVO> dishVOList = BeanUtil.copyToList(dishPage.getRecords(), DishVO.class);
        List<Long> categoryIds = dishVOList.stream().map(DishVO::getCategoryId).collect(Collectors.toList());
        // TODO: 便利集合，查询对应的分类名称
        List<Category> categories = categoryClient.getByIds(categoryIds);
        //将查出来的菜品转化成一个id和名字一一对应的集合，这样就不用查询多次
        Map<Long, String> collect = categories.stream().collect(Collectors.toMap(Category::getId, Category::getName));
        for(DishVO dishVO : dishVOList){
            dishVO.setCategoryName(collect.get(dishVO.getCategoryId()));
        }

//        dishVOList.forEach(dishVO -> {
//            dishVO.setCategoryName();
//        });
        return Result.success(new PageResult(dishPage.getTotal(), dishVOList));
    }
}
